﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace docmgr.WinForm
{
    public partial class AddDocument : Form
    {

        docmgr.BLL.Department depbll=new docmgr.BLL.Department();
        docmgr.BLL.Document docbll = new BLL.Document();

        public AddDocument()
        {
            InitializeComponent();
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

        }

        private void AddDocument_Load(object sender, EventArgs e)
        {
            /**
             public static ArrayList DocType = new ArrayList();
             * 
             */

            if (Convert.ToInt32(Common.curUser.Rows[0]["PositionID"]) != 1)
            {
                HandlerUserTbx.Visible = false;
                label4.Visible = false;
                ArrayList doc=new ArrayList();
                doc.Add("白头文件");
                Common.initCombox(DocTypecombobox,doc);
            }
            else
            {
                Common.initCombox(DocTypecombobox, Common.DocType);
            }
            
            Common.initCombox(SecretLevelcomboBox,Common.SercretLevel);

            DataTable dt = depbll.GetList("id,name","1=1");

            this.DepartmentcomboBox.DataSource = dt;
            this.DepartmentcomboBox.DisplayMember = "Name";
            this.DepartmentcomboBox.ValueMember = "ID";

            this.DocClassIDcomboBox.DataSource = Common.DocClassDT;
            this.DocClassIDcomboBox.DisplayMember = "Name";
            this.DocClassIDcomboBox.ValueMember = "ID";

            int year = Convert.ToInt32(DateTime.Now.ToString().Substring(0, 4));
            for (int i = 0; i < 10;i++ )
                this.YearcomboBox.Items.Add(year-i);
            this.YearcomboBox.SelectedIndex = 0;


        }


        int getCount(String DocType)
        {
            int y = Convert.ToInt32(DateTime.Now.ToString().Substring(0,4));
            DateTime y1 = new DateTime(y,1,1);
            DateTime y2 = new DateTime(y+1,1,1);
            String sqlStr = String.Format("select count(*) c from [Document] where RegDate BETWEEN '{0}' and '{1}' and DocType='{2}'",y1.ToString(),y2.ToString(), DocType);

            DataTable d = SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0];

            return Convert.ToInt32(d.Rows[0]["c"]);//当前总数
        }
        /// <summary>
        /// 
        /// 根据年份 获取时间
        /// </summary>
        /// <param name="DocType"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        int getCount(String DocType,int year)
        {
            int y = Convert.ToInt32(DateTime.Now.ToString().Substring(0, 4));
            DateTime y1 = new DateTime(year, 1, 1);
            DateTime y2 = new DateTime(year + 1, 1, 1);
            String sqlStr = String.Format("select count(*) c from [Document] where RegDate BETWEEN '{0}' and '{1}' and DocType='{2}'", y1.ToString(), y2.ToString(), DocType);
            sqlStr = String.Format("SELECT COUNT (*) c FROM ( SELECT * FROM dbo.Document WHERE dbo.Document.RegDate BETWEEN '{0}' AND '{1}' AND HandleUserID < 1950 AND DocType = '{2}' UNION SELECT * FROM dbo.Document WHERE HandleUserID = {3} AND DocType = '{2}' ) x", y1.ToString(), y2.ToString(), DocType,year);
            DataTable d = SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0];

            return Convert.ToInt32(d.Rows[0]["c"]);//当前总数
        }
        private void AddButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定文件标题、密级、份数、页数等信息正确吗？", "确定添加", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }

            String DocName=DocNameTextBox.Text;
            String Remark = RemarkTextBox.Text;
            String RegDate = DateTime.Now.ToString();
            int UserID = Convert.ToInt32(Common.curUser.Rows[0]["ID"]);
            String SysSerialNumber = SysSerialNumbertbx.Text;//这个没什么用处了
            String DocSerialNumber = DocSerialNumberTextBox.Text;//这个需要进行单独的计算
            String DocType = (String)DocTypecombobox.SelectedItem;

            
            int HandleUserID = Convert.ToInt32(Common.curUser.Rows[0]["ID"]);

            if(HandlerUserTbx.Text!="")
            {
                //如果不为空的话，那么就是默认当前
                DataTable tabel = SQLHelper.ExecuteDataSet(SQLHelper.connString, "select ID from [User] where Username= '" + HandlerUserTbx.Text + "'").Tables[0];

                if (tabel.Rows.Count == 0)
                {
                    MessageBox.Show("不存在用户名" + HandlerUserTbx.Text);
                    return;
                }
                else
                    HandleUserID = Convert.ToInt32(tabel.Rows[0]["ID"]);

            }
            //作为年份的象征。就酱紫吧、
            //
            int year = Convert.ToInt32(DateTime.Now.ToString().Substring(0, 4));
             
            if((String) DocTypecombobox.SelectedItem!="收文")
            {
                DocSerialNumber = "" + (getCount((String)DocTypecombobox.SelectedItem, year - this.YearcomboBox.SelectedIndex) + 1);
                if (DocType == "发文")  DocSerialNumber="装计"+DocSerialNumber+"号";
                if (DocType == "函")  DocSerialNumber="装计函"+DocSerialNumber+"号";
                if (DocType == "呈批件")  DocSerialNumber="装计"+DocSerialNumber+"号";
                if (DocType == "合同") DocSerialNumber = "装计" + DocSerialNumber + "号";
            }

            String SecretLevel = (String)SecretLevelcomboBox.SelectedItem;
            int DepartmentID = Convert.ToInt32(Common.curUser.Rows[0]["DepartmentID"]);
            
            int PageNumber =  Convert.ToInt32(PageNumberNumericUpDown.Value);
            
            String Status = "在库";/**这个需要根据角色权限判断一下，目前先写死，一律写为在库*/
            if (Convert.ToInt32(Common.curUser.Rows[0]["PositionID"]) != 1)
                Status = "传阅";//如果不是管理员状态，则是传阅。
            String Code = "";
            if (DocType == "收文") Code += "SW";
            if (DocType == "发文") Code += "FW";
            if (DocType == "函") Code += "HAN";
            if (DocType == "呈批件") Code += "CPJ";
            if (DocType == "白头文件") Code += "BTWJ";
            if (DocType == "合同") Code += "HT";
            Code += (DepartmentID<10?"0":"") + DepartmentID;//如果是的话，就是两位数字；
            Code += Common.Date2Str(DateTime.Today);
            
            String sqlStr = "select count(*) c  from [Document] where RegDate > ' " + DateTime.Today+"'";

            int cou =Convert.ToInt32(SQLHelper.ExecuteDataSet(SQLHelper.connString, sqlStr).Tables[0].Rows[0]["c"]);
            Code += "" + (cou + 1);
           

            String OutSideDepartMent = OutSideDepartMenttbx.Text;
            int Portion = Convert.ToInt32(PortionNumericUpDown.Value);

            int DocClassID = Convert.ToInt32(DocClassIDcomboBox.SelectedValue);
            if (DocName == "" || DocSerialNumber=="")
            {
                ///无所谓了，不做检查了，爱咋咋地。
                ///酱紫。
                ///既然可以为空，就不检查了
                ///
                if(SecretLevel!="绝密")
                {
                    MessageBox.Show("字段不能为空");
                    return;
                }

            }

            String Fileds = "DocName,Remark,RegDate,UserID,SysSerialNumber,DocSerialNumber,SecretLevel,DepartmentID,DocType,PageNumber,Status,Code,HandleUserID,OutSideDepartMent,Portion,DocClassID";
            String sqlString = String.Format("insert [Document] ({0}) values('{1}','{2}','{3}',{4},'{5}','{6}','{7}',{8},'{9}',{10},'{11}','{12}',{13},'{14}',{15},{16})",
                Fileds, DocName, Remark, RegDate, UserID, SysSerialNumber, DocSerialNumber, SecretLevel, DepartmentID, DocType, PageNumber, Status, Code, year - this.YearcomboBox.SelectedIndex, OutSideDepartMent, Portion, DocClassID);
                                                                                                                                                          ////这个位置代表着code编码，作为一个被废弃的位置，现在被用来表示年份。
            try
            {
                int res=SQLHelper.ExecuteSql(SQLHelper.connString, sqlString);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                ArrayList img = new ArrayList();
                Fileds = "DocID,No,HandlerUserID,Status,Code";
                int DocID = Convert.ToInt32(SQLHelper.ExecuteDataSet(SQLHelper.connString, "select ID from [Document] where Code= '" + Code + "'").Tables[0].Rows[0]["ID"]);
                sqlString = String.Format("insert [DocHandler] ({0}) values ", Fileds);
                for(int i=1;i<=Portion;i++)
                {
                    if (i != 1)
                        sqlString += " , ";///多加空格终归是没错的。呵呵大、

                    sqlString += String.Format("( {0},{1},{2},'{3}','{4}' )", DocID, i, HandleUserID, Status,Code+"-"+i);

                    img.Add(new imageDocument((String)Common.curUser.Rows[0]["Name"], Code + "-" + i));
                }

                SQLHelper.ExecuteSql(SQLHelper.connString, sqlString);
                //imageDocument img = new imageDocument((String)Common.curUser.Rows[0]["Name"], Code);
                ///打印标签
                ///
                try
                {
                    foreach (imageDocument igd in img)
                        igd.Print();//就酱紫。。呵呵大
                }
                catch(Exception ex11)
                {
                    MessageBox.Show("打印异常");
                    Common.Endding();
                }
                this.Close();//调用打印机，结束打印
            }

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void DocTypecombobox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Convert.ToString(DocTypecombobox.SelectedItem) == "收文")
            {
                DocSerialNumberLabel.Visible = true;
                DocSerialNumberTextBox.Visible = true;
                DepartmentIDLabel.Visible = true; 
                OutSideDepartMenttbx.Visible = true;

                SysSerialNumberlb.Visible = true;
                SysSerialNumbertbx.Visible = true;

                
            }
            else
            {
                DocSerialNumberTextBox.Visible = false;
                DocSerialNumberLabel.Visible = false;
                DepartmentIDLabel.Visible = false; 
                OutSideDepartMenttbx.Visible = false;

                SysSerialNumberlb.Visible = false;
                SysSerialNumbertbx.Visible = false;
            }

        }

        private void DocTypecombobox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            
        }

        private void OutSideDepartMenttbx_TextChanged(object sender, EventArgs e)
        {

        }

        private void SecretLevelcomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(Convert.ToString(SecretLevelcomboBox.SelectedItem)=="绝密")
            {
                reset();
                DocNameTextBox.ReadOnly = true;
                PageNumberNumericUpDown.ReadOnly = true;
                PortionNumericUpDown.ReadOnly = true;
                RemarkTextBox.ReadOnly = true;
                //DocSerialNumberTextBox.ReadOnly = true;
                //OutSideDepartMenttbx.ReadOnly = true;
                SysSerialNumbertbx.ReadOnly = true;
            }
            else
            {
                DocNameTextBox.ReadOnly = false;
                PageNumberNumericUpDown.ReadOnly = false;
                PortionNumericUpDown.ReadOnly = false;
                RemarkTextBox.ReadOnly = false;
                //DocSerialNumberTextBox.ReadOnly = false;
                //OutSideDepartMenttbx.ReadOnly = false;
                SysSerialNumbertbx.ReadOnly = false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            reset();
        }

        void reset()
        {
            DocNameTextBox.Text = "";
            RemarkTextBox.Text = "";
            //DocSerialNumberTextBox.Text = "";
            //OutSideDepartMenttbx.Text = "";
            SysSerialNumbertbx.Text = "";
        }

        private void AddDocument_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {

            }
        }

        private void YearcomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
